package com.bluefox.uac.service.impl;

import com.bluefox.uac.model.LoginBean;
import com.bluefox.uac.model.User;
import com.bluefox.uac.security.CustomAuthenticationToken;
import com.bluefox.uac.security.LoginUserBean;
import com.bluefox.uac.service.AuthenticationService;
import com.bluefox.uac.service.UserService;
import com.bluefox.uac.utils.EncryptUtil;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author SF  创建时间: 2019/12/4 13:55
 */
@Service
@Transactional
public class AuthenticationServiceImpl implements AuthenticationService {

   // @Value("${system.secret}")
    private String secret="hospital";
    @Resource
    private UserService userService;
    @Override
    public CustomAuthenticationToken clientUserLogin(LoginBean authBean) {
        final  User user = this.userService.findByUserName(authBean.getUsername());


        if (  null==user) {
            throw new UsernameNotFoundException("用户名或密码错误!");

        } else {
            if(!authBean.getPassword().equals(user.getPassword())){
                throw new UsernameNotFoundException("用户名或密码错误!");
            }
            if (user.isAccountNonLocked()) {
                throw new DisabledException("帐户已禁用.");
            } else {
                final CustomAuthenticationToken token = new CustomAuthenticationToken();
                token.setAuthenticated(true);
                token.setNonceToken(EncryptUtil.aesEncryptToString(user.getId().toString(), this.secret));
                final LoginUserBean bean = new LoginUserBean();
                bean.setAccountType(authBean.getAccountType());
                bean.setUsername(user.getUsername());

                bean.setFullname(user.getFullName());

                List<String> roles1 = this.userService.getUserRoles(user.getUsername());
                final Collection<SimpleGrantedAuthority> roles11 = new ArrayList<>();
                for (final String role : roles1) {
                    roles11.add(new SimpleGrantedAuthority(role));
                }
                bean.setPassword(user.getPassword());
                bean.setRoles(roles11);
                token.setDetails(bean);
                return token;
            }
        }
    }
}
